import React, { PureComponent } from 'react';
import { message, Spin } from 'antd';
import { DATA_ENTRY, AdvancedSearch, ContentPackage, TabC, NoDataC, NoQueryC } from '../../../comps';
import { connect } from 'dva';
import moment from 'moment';
import CashReport from './cashReport';
import DeviationHandle from './deviationHandle';

@connect(({ cashManagementReportM, productAGroupM, loading }) => ({
  cashManagementReportM,
  productAGroupM,
  loadingD: loading.effects['cashManagementReportM/getDeviationControl'],
}))
export default class CashManagementReport extends PureComponent {
  state = {
    portfolioKey: [], // 用于跳转试算页面回显
    portfolioCodeList: [],
    portfolioCodeListName: [],
    searchData: {},
    storeName: {},
    tabType: '1',
    showTabs: undefined, // 是否展示tab
    firstFlag: false, // 是否第一次点击
  };

  componentDidMount() {
    // 查询租户是否有个券偏离度条目
    this.getConfigured();
    // 适配用户视图跳转至,定位指定的产品、日期
    if (sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      if (obj.type == '5') {
        this.state.dateRef?.setDate(moment(obj.cashReportTime));
        this.productRef.props.form.setFieldsValue({
          portfolioList: [obj.productId],
        });
        this.state.searchData.time = moment(obj.cashReportTime).format('YYYYMMDD');
        this.setState({
          portfolioCodeList: [obj.productCode],
          searchData: this.state.searchData,
          timeStamp: new Date().getTime(),
        });
        // 查询个券偏离度
        this.getDeviationControl({
          portfolioCodeList: [obj.productCode],
          time: moment(obj.cashReportTime).format('YYYYMMDD'),
          timeStamp: new Date().getTime(),
        });
        sessionStorage.removeItem('jumpInfo');
      }
    }
    //  更新未读消息---用于用户视图数据
    this.props.dispatch({
      type: 'cashManagementReportM/updateUnreadDate',
      payload: {
        msgType: '5',
      },
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    // 适配用户视图跳转至,定位指定的产品、日期
    if (sessionStorage.getItem('jumpInfo')) {
      const obj = JSON.parse(sessionStorage.getItem('jumpInfo'));
      console.log(obj);
      if (obj.type == '5') {
        this.state.dateRef?.setDate(moment(obj.cashReportTime));
        this.productRef.props.form.setFieldsValue({
          portfolioList: [obj.productId],
        });
        this.state.searchData.time = moment(obj.cashReportTime).format('YYYYMMDD');
        this.setState({
          portfolioCodeList: [obj.productCode],
          searchData: this.state.searchData,
          timeStamp: new Date().getTime(),
        });
        // 查询个券偏离度
        if (this.state.showTabs)
          this.getDeviationControl({
            portfolioCodeList: [obj.productCode],
            time: moment(obj.cashReportTime).format('YYYYMMDD'),
            timeStamp: new Date().getTime(),
          });
        sessionStorage.removeItem('jumpInfo');
      }
    }
  }

  // 获取租户配置 是否有个券 展示tab
  getConfigured = () => {
    this.props.dispatch({
      type: 'cashManagementReportM/getConfigured',
      payload: {},
      callback: (data) => {
        if (data == 0) {
          // 未展示tab的状态 进行赋值
          if (!this.state.showTabs)
            this.setState({
              showTabs: true, // 展示tab
            });
        } else {
          this.setState({
            showTabs: false, // 展示tab
          });
        }
      },
    });
  };

  // 查询个券偏离度
  getDeviationControl = (props) => {
    const { portfolioCodeList, searchData, firstFlag } = this.state;
    this.setState({
      deviationControl: undefined,
    });
    let obj = props;
    if (!obj) {
      obj = {
        portfolioCodeList,
        time: moment(searchData.time).format('YYYYMMDD'),
      };
    }
    if (!firstFlag) this.setState({ firstFlag: true });
    this.props.dispatch({
      type: 'cashManagementReportM/getDeviationControl',
      payload: {
        ...obj,
      },
      callback: (res) => {
        if (res) {
          if (res.code == 0) {
            // 有报告 则返回0
            if (res.data) {
              const object = res.data;
              this.setState({
                deviationControl: object.deviationControl,
                noDataMsg: undefined,
              });
            }
          } else if (res.code == 1) {
            // 无报告 返回1
            this.setState({
              deviationControl: undefined,
              noDataMsg: res.msg,
            });
          } else {
            this.setState({
              deviationControl: undefined,
              noDataMsg: undefined,
            });
            message.error(res.msg || '查询个券偏离度监测列表失败!');
          }
        } else {
          this.setState({
            deviationControl: undefined,
            noDataMsg: undefined,
          });
          message.error('查询个券偏离度监测列表失败!');
        }
      },
    });
  };

  setSearchData = (params) => {
    this.setState({
      searchData: {
        ...this.state.searchData,
        ...params,
      },
    });
  };

  setSearchName = (params) => {
    this.setState({
      storeName: {
        ...this.state.storeName,
        ...params,
      },
    });
  };

  handPortfolioCodeListChange = (e) => {
    this.setState({
      // 产品组id 给到组合试算用
      prouctGroupId: e?.key,
    });
    this.setState({ msg: '' });
    if (e) {
      const {
        info: { children = [] },
      } = e;
      if (children.length > 0) {
        this.state.searchForm?.setFieldsValue({ portfolioList: [] }); // 重置组合和产品
        this.setState({
          portfolioCodeList: children.map((x) => x.code),
          portfolioCodeListName: children.map((x) => `${x.code}-${x.name}`),
        });
      } else {
        message.destroy();
        message.warning('该组合下无产品');
        this.setState({ msg: '该组合下无产品' });
      }
    } else {
      this.setState({
        portfolioCodeList: [],
        portfolioCodeListName: [],
      });
    }
  };

  prodectListChange = (e) => {
    this.setState({
      // 产品组id 给到组合试算用
      prouctGroupId: undefined,
    });
    this.setState({ msg: '' });
    if (e) {
      const { info = [] } = e;
      if (info.length > 0) {
        this.state.searchForm?.resetFields(['portfolioCodeList']); // 重置组合和产品
        this.setState({
          portfolioKey: e.key,
          portfolioCodeList: info.map((x) => x.portfolioCode),
          portfolioCodeListName: info.map((x) => `${x.portfolioCode}-${x.portfolioName}`),
        });
      }
    } else {
      this.setState({
        portfolioCodeList: [],
        portfolioCodeListName: [],
      });
    }
  };

  render() {
    const { showTabs, deviationControl, noDataMsg, firstFlag, portfolioCodeList } = this.state;
    const { loadingD } = this.props;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioCodeList',
          title: '产品组',
          type: DATA_ENTRY.PRODUCTGROUP,
          multiple: false,
          onRef: (ref) => this.setState({ PRODUCTGROUP: ref }),
          onChange: this.handPortfolioCodeListChange,
        },
        {
          dataIndex: 'portfolioList',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          multiple: true,
          onRef: (ref) => (this.productRef = ref),
          onChange: this.prodectListChange,
        },

        {
          type: DATA_ENTRY.SINGLEDATE,
          dataIndex: 'time',
          title: '时间',
          allowClear: false,
          initialValue: moment().subtract(1, 'day'),
          disableEnd: moment().add(1, 'day'),
          onRef: (ref) => {
            this.state.dateRef = ref;
          },
        },
        {
          type: DATA_ENTRY.SELECT,
          dataIndex: 'tmep',
          title: '报告模板',
          initialValue: '1',
          dataSource: [{ title: '现金类报告', value: '1' }],
        },
      ],
      onQuery: (e) => {
        if (this.state.msg) {
          message.destroy();
          message.warning(this.state.msg);
          return;
        }
        if (this.state.portfolioCodeList?.length > 0) {
          if (!e.time) {
            message.error('请选择时间');
            return;
          }
          this.setSearchData({
            time: moment(e.time).format('YYYYMMDD'),
            portfolioCodeList: this.state.portfolioCodeList,
          });
          if (this.state.showTabs)
            this.getDeviationControl({
              time: moment(e.time).format('YYYYMMDD'),
              portfolioCodeList: this.state.portfolioCodeList,
            });
          this.setSearchName({
            // 名称来自产品组change事件
            portfolioCodeListName: this.state.portfolioCodeListName,
          });
          this.setState({
            timeStamp: new Date().getTime(),
          });
        } else {
          message.error('请选择产品或产品组');
        }
      },
      onClear: () => {
        this.setState({
          portfolioCodeList: [],
          portfolioCodeListName: [],
          firstFlag: false,
          noDataMsg: undefined,
          timeStamp: '',
        });
      },
      onRef: (ref) => {
        this.AdvancedSearch = ref;
      },
    };
    return (
      <ContentPackage
        title='现金管理理财新规报告'
        contentHtml={
          <div className='cashManagementReport' style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
            <div>
              <AdvancedSearch {...searchProps} onRef={(ref) => this.setState({ searchForm: ref.props.form })} />
            </div>
            {showTabs ? (
              <div style={{ marginTop: '20px' }}>
                <TabC
                  bottomHeight={false}
                  tabSource={[
                    {
                      title: '报告内容',
                      key: '1',
                      content: (
                        <CashReport
                          type={'1'}
                          storeName={this.state.storeName}
                          {...this.state.searchData}
                          timeStamp={this.state.timeStamp}
                          prouctGroupId={this.state.prouctGroupId}
                          portfolioCodeListName={this.state.portfolioCodeListName}
                          portfolioCodeList={this.state.portfolioCodeList}
                          portfolioKey={this.state.portfolioKey}
                        />
                      ),
                    },
                    {
                      title: '偏离度处理',
                      key: '2',
                      content: (
                        <div style={{ marginTop: '20px' }}>
                          {!firstFlag ? (
                            <NoQueryC />
                          ) : noDataMsg ? (
                            <NoDataC title={noDataMsg} />
                          ) : deviationControl ? (
                            <DeviationHandle portfolioCodeList={portfolioCodeList} data={deviationControl} getDeviationControl={this.getDeviationControl} />
                          ) : (
                            <Spin spinning={loadingD}>
                              <div style={{ height: '200px' }}></div>
                            </Spin>
                          )}
                        </div>
                      ),
                    },
                  ]}
                  activeKey={this.state.tabType}
                  onChange={(key) => {
                    this.setState({
                      tabType: key,
                    });
                  }}
                />
              </div>
            ) : showTabs == undefined ? null : (
              <CashReport
                type={'1'}
                storeName={this.state.storeName}
                {...this.state.searchData}
                timeStamp={this.state.timeStamp}
                prouctGroupId={this.state.prouctGroupId}
                portfolioCodeListName={this.state.portfolioCodeListName}
                portfolioCodeList={this.state.portfolioCodeList}
                portfolioKey={this.state.portfolioKey}
              />
            )}
          </div>
        }
      />
    );
  }
}
